﻿using MapleLeaf.Core.Const;
using MapleLeaf.Core.Filter;
using MapleLeaf.Core.Handler;
using MapleLeaf.Core.Swagger;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using System.Reflection;

namespace DiLe.Mes.Cloud.Components {
    /// <summary>
    /// 
    /// </summary>
    public static class SwaggerComponent {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        public static void AddSwaggerComponent(this WebApplicationBuilder builder) {
            builder.Services.AddSwaggerGen(options => {

                options.OrderActionsBy((apiDesc) => $"{apiDesc.ActionDescriptor.RouteValues["controller"]}_{apiDesc.HttpMethod}");

                options.DocumentFilter<SwaggerIgnoreFilter>();
                foreach (var item in SwaggerExtensions.GetCloudSwaggerApiInfos()) {
                    options.SwaggerDoc(item.UrlPrefix, item.OpenApiInfo);
                }
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() {
                    Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement {{
                        new OpenApiSecurityScheme{
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        Array.Empty<string>()
                    }});
                var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
                var modelXmlFilename = $"DiLe.Mes.Model.xml";
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, modelXmlFilename), true);
                var mapleLeafCoreXmlFilename = $"MapleLeaf.Core.xml";
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, mapleLeafCoreXmlFilename), true);

                options.CustomOperationIds(apiDesc => {
                    var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor;
                    return controllerAction?.ControllerName + "-" + controllerAction?.ActionName;
                });
            });
        }
    }
}
